package com.uyayo.portal.controller;

import com.uyayo.framework.common.exception.EmailMultipleException;
import com.uyayo.framework.common.exception.PhoneMultipleException;
import com.uyayo.framework.common.exception.UserMultipleException;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.common.util.MD5Util;
import com.uyayo.framework.web.annotation.GetRequestInfo;
import com.uyayo.framework.web.constants.WebConstants;
import com.uyayo.framework.web.model.RequestInfo;
import com.uyayo.portal.biz.ParamBiz;
import com.uyayo.portal.shiro.MemberUsernamePasswordToken;
import com.uyayo.portal.biz.SmsEmailBiz;
import com.uyayo.system.config.service.SysParamService;
import com.uyayo.ucenter.entity.Member;
import com.uyayo.ucenter.entity.MemberState;
import com.uyayo.ucenter.service.MemberService;
import com.uyayo.portal.biz.CheckBiz;
import com.uyayo.portal.vo.EmailRegisterVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * 
 * Title: RegisterController
 * Description:注册控制器
 * Company: www.lelekeji.com
 *
 * @author 乐乐科技.胡逢君
 * @date 2016-4-23下午4:03:35
 * @version 1.0
 */
@Controller("registerController")
@RequestMapping("/register")
public class RegisterController {
	private final MemberService memberService;
	private final SysParamService paramsService;

	private final ParamBiz paramBiz;

	private final MessageSource messageSource;

	private final CheckBiz checkBiz;

	private final SmsEmailBiz smsEmailBiz;

	@Autowired
	public RegisterController(MemberService memberService, SysParamService paramsService, ParamBiz paramBiz, MessageSource messageSource, CheckBiz checkBiz, SmsEmailBiz smsEmailBiz) {
		this.memberService = memberService;
		this.paramsService = paramsService;
		this.paramBiz = paramBiz;
		this.messageSource = messageSource;
		this.checkBiz = checkBiz;
		this.smsEmailBiz = smsEmailBiz;
	}

	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView register(ModelAndView modelAndView,HttpServletRequest request,String redirectURL) throws IOException, ServletException {
		String WEB_REGISTER_PAGE = paramsService.getSysParamValueByCode("WEB_REGISTER_PAGE");  	//注册页面
		String WEB_INDEX = paramsService.getSysParamValueByCode("WEB_INDEX");				//首页

		if (redirectURL == null || redirectURL.equals("")){
			
			redirectURL = WEB_INDEX;
		}
		modelAndView.addObject("redirectURL", redirectURL);
		modelAndView.setViewName(paramBiz.getWebsitTemplatesPrefix()+WEB_REGISTER_PAGE);
		return modelAndView;
	}

	@RequestMapping(value = "verify/{username}",method=RequestMethod.GET)
	public ModelAndView registerVerify(ModelAndView modelAndView, String redirectURL, @PathVariable("username") String username) throws IOException, ServletException {
		String WEB_INDEX = paramsService.getSysParamValueByCode("WEB_INDEX");				//首页

		if (redirectURL == null || redirectURL.equals("")){
			redirectURL = WEB_INDEX;
		}
		modelAndView.addObject("redirectURL", redirectURL);
		modelAndView.addObject("username",username);
		modelAndView.setViewName(paramBiz.getWebsitTemplatesPrefix()+"/register_verify");
		return modelAndView;
	}

	@RequestMapping(value = "verify/{username}/{verifyCode}",method=RequestMethod.GET)
	public ModelAndView registerVerify(ModelAndView modelAndView, HttpServletRequest request, String redirectURL, @PathVariable("verifyCode") String verifyCode, @PathVariable("username") String username) throws IOException, ServletException {
		String WEB_REGISTER_PAGE = paramsService.getSysParamValueByCode("WEB_REGISTER_PAGE");  	//注册页面
		String WEB_INDEX = paramsService.getSysParamValueByCode("WEB_INDEX");				//首页

		if (redirectURL == null || redirectURL.equals("")){

			redirectURL = WEB_INDEX;
		}

		Member member = memberService.getMemberByUsername(username);
		if(member!=null && Objects.equals(member.getVerifyCode(),verifyCode)){
			try {
				member.setEmailVerifyStatus(1);
				memberService.updateMember(member);
			} catch (EmailMultipleException e) {
				e.printStackTrace();
			} catch (PhoneMultipleException e) {
				e.printStackTrace();
			} catch (UserMultipleException e) {
				e.printStackTrace();
			}
			MemberUsernamePasswordToken token = new MemberUsernamePasswordToken(username,member.getPassword(),true,request.getLocalAddr());
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
			modelAndView.setViewName("redirect:"+redirectURL);
			return modelAndView;
		}
		modelAndView.addObject("redirectURL", redirectURL);
		modelAndView.setViewName(paramBiz.getWebsitTemplatesPrefix()+WEB_REGISTER_PAGE);
		return modelAndView;
	}


	@ResponseBody
	@RequestMapping(method=RequestMethod.POST)
	public Result register(HttpServletRequest request,@Validated EmailRegisterVO emailRegisterVO, Errors errors, HttpSession session ,@GetRequestInfo RequestInfo requestInfo) throws IOException, ServletException {

		try {

			if (errors.hasErrors()) {
				return new Result(400,errors.getFieldError().getDefaultMessage());
			}
			String captchaSession = (String) session.getAttribute(WebConstants.CAPTCHA_SESSION);

			String captcha = emailRegisterVO.getCaptcha();
			if(captcha !=null && !captcha.equals(captchaSession)){
				return new Result(400,messageSource.getMessage("captcha.error",null, request.getLocale()));
			}else{
				request.getSession().removeAttribute(WebConstants.CAPTCHA_SESSION);
			}
			String username = emailRegisterVO.getUsername();
			String email = emailRegisterVO.getEmail();

			if(!checkBiz.checkMemberUsernameExist(username)){
				return new Result(400,"用户名已存在，请更换！");
			}

			if(!checkBiz.checkMemberEmailExist(email)){
				return new Result(400,"邮箱已存在，请更换！");
			}
			int code = (int)((Math.random()*9+1)*100000);

			Member member = new Member();
			member.setUsername(username);
			String password_ = MD5Util.md5(emailRegisterVO.getPassword());

			member.setEmail(email);
			member.setPassword(password_);
			member.setVerifyCode(String.valueOf(code));
			member.setCreateTime(new Date());
			member.setCreateBy(username);
			MemberState memberState = new MemberState();
			memberState.setCreateTime(new Date());
			memberState.setCreateBy(username);
			memberState.setLoginCount(0);
			memberState.setRegisterDevice(1);
			memberState.setRegisterIp(requestInfo.getRequestIp());
			memberState.setRegisterDomain(requestInfo.getDomainName());
			memberService.saveMember(member,memberState);
			smsEmailBiz.sendEmail(username,String.valueOf(code),email,new Date());
			return new Result(200,"注册成功，请验证邮箱！","/register/verify/"+username);
        }catch (Exception e) {
        	e.printStackTrace();
			return new Result(400,"登录失败，服务器发生异常，请管理员联系！");
		}
	}
}
